#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Description:
import os
import logging
from datetime import datetime
from termcolor import colored


class Logger:
    _instance = None

    def __new__(cls, log_dir="logs", log_level="DEBUG"):
        """确保 Logger 只初始化一次"""
        if not cls._instance:
            cls._instance = super(Logger, cls).__new__(cls)
            cls._instance._init_logger(log_dir, log_level)
        return cls._instance

    def _init_logger(self, log_dir, log_level):
        """初始化日志配置"""
        # 获取当前日期，用于生成日志文件名
        self.current_date = datetime.now().strftime("%Y-%m-%d")

        # 确保日志目录存在
        self.ensure_log_directory_exists(log_dir)

        # 设置日志文件名
        self.log_filename = f"qdfs_test_{self.current_date}.log"

        # 配置日志
        self.logger = logging.getLogger("QDFS_LOGGER")
        self.logger.setLevel(self.get_log_level(log_level))

        # 创建日志文件处理器
        log_path = os.path.join(log_dir, self.log_filename)
        file_handler = logging.FileHandler(log_path)
        file_handler.setLevel(self.get_log_level(log_level))

        # 设置日志格式
        formatter = logging.Formatter('[%(levelname)s = %(asctime)s] %(message)s',
                                      datefmt='%Y-%m-%d %H:%M:%S')
        file_handler.setFormatter(formatter)

        # 将文件处理器添加到 logger
        self.logger.addHandler(file_handler)

        # 创建终端输出的 StreamHandler
        console_handler = logging.StreamHandler()
        console_handler.setLevel(self.get_log_level(log_level))
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)

    def ensure_log_directory_exists(self, log_dir):
        """确保日志目录存在，不存在则创建"""
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)

    def get_log_level(self, log_level):
        """获取日志级别"""
        levels = {
            "DEBUG": logging.DEBUG,
            "INFO": logging.INFO,
            "WARNING": logging.WARNING,
            "ERROR": logging.ERROR,
            "CRITICAL": logging.CRITICAL
        }
        return levels.get(log_level.upper(), logging.DEBUG)

    def info(self, message):
        """记录 INFO 级别的日志"""
        self.logger.debug(colored(f"{message}", 'blue'))

    def success(self, message):
        """记录 SUCCESS 级别的日志"""
        self.logger.info(colored(f"{message}", 'green'))

    def warn(self, message):
        """记录 SUCCESS 级别的日志"""
        self.logger.warning(colored(f"{message}", 'yellow'))

    def error(self, message):
        """记录 ERROR 级别的日志"""
        self.logger.error(colored(f"{message}", 'red'))
